package com.control.control;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;

import twitter4j.Twitter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

import com.control.controlprueba.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends FragmentActivity implements LoaderCallbacks<Cursor>, LocationListener {

	
    //private AdView myAdView;
	GoogleMap googleMap; //referencia al mapa
	JSONArray ubicaciones; 
	private LocationManager locationManager;
    private String proveedor;
    TelephonyManager tm;
    String imei;
    final Context context = this; 
    String hora; 
    String minuto;
    String linea ="Linea 30";
    LatLng punto;
    Marker aEliminar;
    Circle aEliminarCirculo;
    List<Marker> marcas; //lista de todas las marcas del mapa
    List<LatLng> listaPuntos; //lista de todos los puntos del mapa
    Location location; 
    HashMap<Marker, String> marcadores= new HashMap<Marker, String>(); //obtener marcador por medio del uid
    Twitter mTwitter;
    boolean camara=true;
    LatLng posicionMarker;
    public TimePicker timePicker;
    int timePickerHora;
    int timePickerMinuto;
    ImageView image;
    
    
    //Variables
    LatLng inicio;
    LatLng fin;
    List<LatLng> puntosDelBus;
    List<LatLng> listEAyala;
    List<LatLng> listRArgentina;
    List<Linea> lineas;
    Linea lineaSeleccionada;
    List<Bus> buses;
    HashMap<Bus, Marker> busMarker;
    
    //Para pruebas
    int[] indices= {0,30, 0, 20}; 
    int indice = 0;
    int color = Color.GREEN;
    Marker posicionBus;
    final int INTERVALO = 1000;
    /**
     * Se inicializan las variables
     */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
        
		busMarker = new HashMap<Bus, Marker>();
		
		lineas = new ArrayList<Linea>();
		buses = new ArrayList<Bus>();
		
		Linea linea27 = new Linea();
		linea27.setLinea("Linea 27");
		
		Linea linea30 = new Linea();
		linea30.setLinea("Linea 30");
		
		Bus linea27coche1 = new Bus();
		linea27coche1.setId("1");
		linea27coche1.setLinea("Linea 27");
		linea27coche1.setCoche("1");
		
		Bus linea27coche2 = new Bus();
		linea27coche2.setId("2");
		linea27coche2.setLinea("Linea 27");
		linea27coche2.setCoche("2");
			
		Bus linea30coche1 = new Bus();
		linea30coche1.setId("3");
		linea30coche1.setLinea("Linea 30");
		linea30coche1.setCoche("1");
		
		Bus linea30coche2 = new Bus();
		linea30coche2.setId("4");
		linea30coche2.setLinea("Linea 30");
		linea30coche2.setCoche("2");
		
		buses.add(linea27coche1);
		buses.add(linea27coche2);
		linea27.setBuses(buses);
		
		linea30.getBuses().add(linea30coche1);
		linea30.getBuses().add(linea30coche2);
		
		lineas.add(linea27);
		lineas.add(linea30);
		
		listEAyala=new ArrayList<LatLng>();
        listEAyala.add(new LatLng(-25.3242414,-57.5524845));
        listEAyala.add(new LatLng(-25.3246681,-57.5518193));
        listEAyala.add(new LatLng(-25.3250948,-57.550961));
        listEAyala.add(new LatLng(-25.3254439,-57.5502958));
        listEAyala.add(new LatLng(-25.3260064,-57.5493946));
        listEAyala.add(new LatLng(-25.3263555,-57.548708));
        listEAyala.add(new LatLng(-25.3271119,-57.5475064));
        listEAyala.add(new LatLng(-25.3278489,-57.5462189));
        listEAyala.add(new LatLng(-25.3284501,-57.5452533));
        listEAyala.add(new LatLng(-25.3297689,-57.5435152));
        listEAyala.add(new LatLng(-25.3306223,-57.5422921));
        listEAyala.add(new LatLng(-25.3316502,-57.5411119));
        listEAyala.add(new LatLng(-25.3326005,-57.5397172));
        listEAyala.add(new LatLng(-25.3333181,-57.5382795));
        listEAyala.add(new LatLng(-25.3337448,-57.5371637));
        listEAyala.add(new LatLng(-25.3342297,-57.5359406));
        listEAyala.add(new LatLng(-25.3346176,-57.534975));
        listEAyala.add(new LatLng(-25.3350249,-57.5336446));
        listEAyala.add(new LatLng(-25.3354516,-57.5326361));
        listEAyala.add(new LatLng(-25.3359171,-57.5313916));
        listEAyala.add(new LatLng(-25.3363244,-57.53019));
        listEAyala.add(new LatLng(-25.3370226,-57.5283661));
        listEAyala.add(new LatLng(-25.3377208,-57.5267353));
        listEAyala.add(new LatLng(-25.338322,-57.5251689));
        listEAyala.add(new LatLng(-25.3386517,-57.5239887));
        listEAyala.add(new LatLng(-25.3390977,-57.5229373));
        listEAyala.add(new LatLng(-25.3396407,-57.5214138));
        listEAyala.add(new LatLng(-25.3409982,-57.5196114));
        listEAyala.add(new LatLng(-25.342631, -57.517914));
        listEAyala.add(new LatLng(-25.344531, -57.516669));
        listEAyala.add(new LatLng(-25.345637, -57.515167));
        listEAyala.add(new LatLng(-25.351493, -57.511820));
        
        listRArgentina=new ArrayList<LatLng>();
        listRArgentina.add(new LatLng(-25.2969904,-57.5779396));
        listRArgentina.add(new LatLng(-25.2990468,-57.5792271));
        listRArgentina.add(new LatLng(-25.3005212,-57.5800854));
        listRArgentina.add(new LatLng(-25.3031207,-57.5817162));
        listRArgentina.add(new LatLng(-25.3044786,-57.5825745));
        listRArgentina.add(new LatLng(-25.3059917,-57.5833899));
        listRArgentina.add(new LatLng(-25.3075048,-57.5842911));
        listRArgentina.add(new LatLng(-25.3088627,-57.5851065));
        listRArgentina.add(new LatLng(-25.3097162,-57.5856215));
        listRArgentina.add(new LatLng(-25.3109577,-57.5863511));
        listRArgentina.add(new LatLng(-25.3125483,-57.5873382));
        listRArgentina.add(new LatLng(-25.3137897,-57.5881965));
        listRArgentina.add(new LatLng(-25.3149147,-57.5890977));
        listRArgentina.add(new LatLng(-25.3159233,-57.5898273));
        listRArgentina.add(new LatLng(-25.3166604,-57.5905569));
        listRArgentina.add(new LatLng(-25.3179406,-57.5913294));
        listRArgentina.add(new LatLng(-25.318988,-57.5921019));
        listRArgentina.add(new LatLng(-25.3199966,-57.5929602));
        listRArgentina.add(new LatLng(-25.3207337,-57.5934323));
        listRArgentina.add(new LatLng(-25.3218587,-57.5942906));
        listRArgentina.add(new LatLng(-25.3230612,-57.5950202));
        listRArgentina.add(new LatLng(-25.3241862,-57.5958356));
		
		// Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
		
		// Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available        	
        	proveedor="";
        	imei="";
        	hora="";
        	minuto="";
        	punto= new LatLng(0, 0);
        	ubicaciones= new JSONArray();
       	 	listaPuntos = new ArrayList<LatLng>();
       	 	marcas = new ArrayList<Marker>();
       	 	
	       	marcadores= new HashMap<Marker, String>();
       	 	
            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true); 
            
            googleMap.getUiSettings().setZoomControlsEnabled(true);

            googleMap.getUiSettings().setCompassEnabled(true);  
            
            googleMap.getUiSettings().setAllGesturesEnabled(true);
            
            //obtenemos la ubicacion actual para ver si esta en alerta
            // Tomamos el location manager
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            // Definimos un objeto del tipo criteria para que este elija cual locatioin provider nos
            // conviene utilizar
            Criteria criteria = new Criteria();
            proveedor = locationManager.getBestProvider(criteria, false);
            Location ubicacion = locationManager.getLastKnownLocation(proveedor);
            
            // vemos si se inicializamos la ubicacion
            if (ubicacion != null) {
              System.out.println("Proveedor  " + proveedor + " ha sido seleccionado.");
              //onLocationChanged(ubicacion);
            } else {
				Toast.makeText(getBaseContext(), "UBICACION NO ENCOTNRADA", Toast.LENGTH_SHORT).show();

            }
            //mostrar imei
            tm = (TelephonyManager) getSystemService(android.content.Context.TELEPHONY_SERVICE);
            imei = tm.getDeviceId();
        }        
        
        googleMap.setOnMapClickListener(new OnMapClickListener()  {
			
			@Override
			public void onMapClick(final LatLng point) {		

				//Se abre el popup para seleccionar la linea
				final Dialog dialog = new Dialog(context);
				dialog.setContentView(R.layout.confirmar);
				dialog.setTitle("Seleccione una Linea");

				image = (ImageView) findViewById(R.id.imagen);
				Spinner tipos = (Spinner) dialog.findViewById(R.id.tipo);
				
				List<String> listaLineas = new ArrayList<String>();
				for(Linea linea: lineas){
					listaLineas.add(linea.getLinea());
				}
								
			    ArrayAdapter<String> aa = new ArrayAdapter<String>(context,
		                android.R.layout.simple_spinner_item, listaLineas);
		        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		        tipos.setAdapter(aa);
		        
		        //Una vez que se selecciona una linea
			    tipos.setOnItemSelectedListener(new OnItemSelectedListener(){
			    	
			    	public void onItemSelected(AdapterView<?> parent, View view, 
			                int pos, long id) {
			    		//Toast.makeText(context, parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
			    		String elegida= (String) parent.getItemAtPosition(pos);
			    		for(Linea linea: lineas){
			    			if(linea.getLinea().equals(elegida)){
			    				lineaSeleccionada = linea;
			    			}
			    		}

			        }
			    	
			        public void onNothingSelected(AdapterView<?> parent) {
			            // Another interface callback
			        }
			    });
			    
				Button dialogButtonOk = (Button) dialog.findViewById(R.id.dialogButtonOK);
				Button dialogButtonCancel = (Button) dialog.findViewById(R.id.dialogButtonCancel);
				dialogButtonOk.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						googleMap.clear();
						lineaSeleccionada();
						
					}
				});
				dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
	 
				dialog.show();

			}
		});	

        googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {				
			@Override
			public void onMapLongClick(LatLng point) {
				
				
			}
		});
    }
	
	public void lineaSeleccionada(){
		
		indices[0] = 0;
		indices[1] = 30;
		indices[2] = 0;
		indices[3] = 20;
		busMarker = new HashMap<Bus, Marker>();
		for(Bus bus: lineaSeleccionada.getBuses()){
			//bus.setPosicion(posicion);
			
			new myAsyncTask().execute(bus);
		}
		
	}
	
	private class myAsyncTask extends AsyncTask<Bus, Void, Bus> { 
		@Override protected void onPreExecute() { 
			super.onPreExecute(); 
			
			} 
		// Executed on a special thread and all your // time taking tasks should be inside this method 
		@Override protected Bus doInBackground(Bus... bus) { 
			
			obtenerUltimaPosicion(bus[0]);
			return bus[0]; 
			} // Executed on the UI thread after the // time taking process is completed 
		@Override protected void onPostExecute(Bus bus) { 
			super.onPostExecute(bus);
			
			actualizarPosicion(bus);
			
			//Mientras tanto obtiene de los listados, deberia traer del servidor
			if(busMarker!= null && busMarker.size()>0){
				if(bus.id.equals("1")){
					if(indices[0] < listEAyala.size()){
						new myAsyncTask().execute(bus);
					} 
				}
				if(bus.id.equals("2")){
					if(indices[1] > 0){
						new myAsyncTask().execute(bus);
					} 
				}
				if(bus.id.equals("3")){
					if(indices[2] < listRArgentina.size()){
						new myAsyncTask().execute(bus);
					} 
				}
				if(bus.id.equals("4")){
					if(indices[3] > 0){
						new myAsyncTask().execute(bus);
					} 
				}	
			}
			
		}
	}
	/**
	 * Obtiene el ultimo punto del servidor
	 * @param bus
	 */
	public void obtenerUltimaPosicion(Bus bus){
		
		//Aca se realiza la peticion http para obtener la ultima posicion
		
		try {
			Thread.sleep(INTERVALO);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//bus.setPosicion(posicion);
		if(bus.id.equals("1")){
			bus.setPosicion(listEAyala.get(indices[0]));
			indices[0]++;
		}else if(bus.id.equals("2")){
			bus.setPosicion(listEAyala.get(indices[1]));
			indices[1]--;
		}else if(bus.id.equals("3")){
			bus.setPosicion(listRArgentina.get(indices[2]));
			indices[2]++;
		}else if(bus.id.equals("4")){
			bus.setPosicion(listRArgentina.get(indices[3]));
			indices[3]--;
		}
	}
	/**
	 * Actualiza la posicion del bus en el mapa
	 * @param bus
	 */
	public void actualizarPosicion(Bus bus){
		
		Marker marker = null;
		LatLng inicio = null;
		LatLng fin = null;
		if(busMarker.containsKey(bus)){
			marker = busMarker.get(bus);
			inicio = marker.getPosition();
			fin =  bus.getPosicion();
			
			busMarker.get(bus).setPosition(fin);
			googleMap.addPolyline(new PolylineOptions().add(inicio, fin).width(10).color(color));
			
		}else{
			marker = googleMap.addMarker(new MarkerOptions()
			.position(bus.getPosicion())
			.title(bus.getLinea() + "-" + bus.getCoche())
			.draggable(true)
			.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
			busMarker.put(bus, marker);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0,
			Bundle arg1) {
		
		// Uri to the content provider LocationsContentProvider
		Uri uri = LocationsContentProvider.CONTENT_URI;
		
		// Fetches all the rows from locations table
        return new CursorLoader(this, uri, null, null, null, null);

	}


	@Override
	public void onLoadFinished(Loader<Cursor> arg0,
			Cursor arg1) {
		
	}
	
	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		// TODO Auto-generated method stub		
	}	
	
	public void cambiarHibrido(View view) {
		Button cambiar= (Button)view;
		if(cambiar.getText().toString().equals(getResources().getString(R.string.satelite)))
			cambiar.setText(getResources().getString(R.string.mapa));
		else
			cambiar.setText(getResources().getString(R.string.satelite));
		if(googleMap.getMapType()==GoogleMap.MAP_TYPE_HYBRID){
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
		}else{
			googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
		}
	 }
	
	public void info(View view) {
		Intent intentInformacion=new Intent(getApplicationContext(),Informacion.class);
		startActivity(intentInformacion);
	 }
	
	public boolean onOptionsItemSelected(MenuItem item){
		int id = item.getItemId();

		if (id == R.id.informacion) {
			//Toast.makeText(getBaseContext(), "email", Toast.LENGTH_SHORT).show();
			Intent intentInformacion=new Intent(getApplicationContext(),Informacion.class);
			startActivity(intentInformacion);
			return true;
			}
		else
			return false;
	 }
	@Override
	 protected void onResume() {
	   super.onResume();
	   camara=true;
	   locationManager.requestLocationUpdates(proveedor, 0, 0, this);
	   
	 }
	
	 @Override
	 protected void onPause() {
	   super.onPause();
	   locationManager.removeUpdates(this);
	 }
	 @Override
	 protected void onStop() {
	   super.onPause();
	   locationManager.removeUpdates(this);
	 }

	@Override
	public void onLocationChanged(Location location) {
		 this.location=location;
		 if(camara){
			 camara=false;
			 LatLng miLatLng= new LatLng(location.getLatitude(), location.getLongitude());
			 CameraPosition cameraPosition = new CameraPosition.Builder()
			   .target(miLatLng) // seteamos el centro del mapa en la posicion actual
			   .zoom(15) // configuramos el zoom
			   .bearing(location.getBearing()) // seteamos la orientacion hacia el este
			   .tilt(30) // configuramos el angulo de la camara a 30 grados
			   .build(); // Una vez seteado los parametros, construimos el objetos
			  
			        // ubicamos nuestra posicion en el mapa, para que sea centrado ahi, con un angulo y vista
			googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
			
		}
		//googleMap.clear();
		listaPuntos = new ArrayList<LatLng>();
   	 	marcas = new ArrayList<Marker>();
        //new Ubicaciones().execute();

        }

	@Override
	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "Disabled provider " + provider,
			       Toast.LENGTH_SHORT).show();
		
	}


	@Override
	public void onProviderEnabled(String provider) {
		Toast.makeText(this, "Habilitado el nuevo proveedor  " + proveedor,
			       Toast.LENGTH_SHORT).show();
		
	}
	


	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	public void confirmar(LatLng point){
		punto = point;
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	/*
	private class GuardarUbicacion extends AsyncTask<Void, Void, JSONObject> {
		@Override
        protected JSONObject doInBackground(Void... params) { 

    		Calendar fecha = Calendar.getInstance();
    		fecha.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hora));
    		fecha.set(Calendar.MINUTE, Integer.parseInt(minuto));
    		
    		Calendar fechaActual= Calendar.getInstance();
    		String fechaActualString = fechaActual.get(Calendar.YEAR)+"-"+ (fechaActual.get(Calendar.MONTH)+1)+"-"+ fechaActual.get(Calendar.DATE)+" "
    	    		+fechaActual.get(Calendar.HOUR_OF_DAY)+":"+fechaActual.get(Calendar.MINUTE)+":"+fechaActual.get(Calendar.SECOND);
    		
    		if(fechaActual.get(Calendar.HOUR_OF_DAY) < fecha.get(Calendar.HOUR_OF_DAY) ||
    				fechaActual.get(Calendar.HOUR_OF_DAY) == fecha.get(Calendar.HOUR_OF_DAY) &&
    				fechaActual.get(Calendar.MINUTE) < fecha.get(Calendar.MINUTE)){
    			fecha.add(Calendar.DAY_OF_YEAR, -1);
    		}
    		
    		String fechaString= fecha.get(Calendar.YEAR)+"-"+ (fecha.get(Calendar.MONTH)+1)+"-"+ fecha.get(Calendar.DATE)+" "
    		+fecha.get(Calendar.HOUR_OF_DAY)+":"+fecha.get(Calendar.MINUTE)+":"+fecha.get(Calendar.SECOND);
    		//String fechaString = hora+":"+minuto;
    		
    		
    		ContentValues ubicacion= new ContentValues();
    		ubicacion.put("longitud", punto.longitude+"");
    		ubicacion.put("latitud", punto.latitude+"");
    		ubicacion.put("imei", imei);
    		ubicacion.put("fechaActual", fechaActualString);
    		ubicacion.put("fecha", fechaString);
    		ubicacion.put("hora", hora);
    		ubicacion.put("minuto", minuto);
    		UserFunctions userFunction = new UserFunctions();
			try{
	            JSONObject json = userFunction.registerUser(ubicacion);
	            return json;

			}catch(Exception ex){
				ex.printStackTrace();
			}
            return null;
        }
		@Override
        protected void onPostExecute(JSONObject miJson){
			String id="";
			if(miJson!=null){
			try {
				if(miJson.getString("uid")!=null){
					Toast.makeText(getBaseContext(),"Enviando Tweet a @mapacontroles", Toast.LENGTH_SHORT).show();
				}
				else{
					Toast.makeText(getBaseContext(),"Fallo al enviar Tweet", Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		
    		listaPuntos.add(punto);
			}
   		}
    }
    */
}